package com.zyk.leetcode;

import java.util.LinkedList;

/**
 * @author zhangsan
 * @date 2021/4/9 10:37
 */
public class M0303 {

    static class StackOfPlates {

        private LinkedList<LinkedList<Integer>> setOfStacks;
        private int cap;

        public StackOfPlates(int cap) {
            this.setOfStacks = new LinkedList<>();
            this.cap = cap;
        }

        private boolean setIsEmpty() {
            return setOfStacks.isEmpty();
        }

        private boolean lastStackIsFUll() {
            if (setIsEmpty()) {
                return true;
            }
            return setOfStacks.getLast().size() >= cap;
        }

        private boolean lastStackIsEmpty() {
            return setOfStacks.getLast().isEmpty();
        }

        public void push(int val) {
            if (cap <= 0) {
                return;
            }
            if (setIsEmpty() || lastStackIsFUll()) {
                setOfStacks.addLast(new LinkedList<>());
            }
            setOfStacks.getLast().addLast(val);
        }

        public int pop() {
            int val = -1;
            if (setIsEmpty()) {
                return val;
            }
            val = setOfStacks.getLast().removeLast();
            if (lastStackIsEmpty()) {
                setOfStacks.removeLast();
            }
            return val;
        }

        public int popAt(int index) {
            int val = -1;
            if (setIsEmpty() || setOfStacks.size() - 1 < index) {
                return val;
            }
            val = setOfStacks.get(index).removeLast();
            if (setOfStacks.get(index).isEmpty()) {
                setOfStacks.remove(index);
            }
            return val;
        }
    }


    // for test
    public static void main(String[] args) {
        // ["StackOfPlates", "push", "push", "popAt", "pop", "pop"]
        // [[1], [1], [2], [1], [], []]

        StackOfPlates stack = new StackOfPlates(1);
        stack.push(1);
        stack.push(2);
        System.out.println(stack.popAt(1));
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }

}
